<template>
  <div>
    <!-- 搜索框-->
    <el-form :model="form">
      <el-row style="margin-bottom: 20px;">
        <el-col :span="5" class="flex-container">
          <div class="search-label">角色名称：</div>
          <div class="search-input">
            <el-input v-model="form.searchText" @input="getRoles" placeholder="输入角色名称搜索"></el-input>
          </div>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="getRoles">搜索</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="success" @click="showAddModal = true">新增角色</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 角色数据-->
    <el-table :data="roleData" border max-height="500">
      <el-table-column prop="id" label="序号" align="center" width="100"></el-table-column>
      <el-table-column prop="name" label="角色名称" align="center" width="100"></el-table-column>
      <el-table-column prop="description" label="角色描述" align="center" width="300"></el-table-column>

      <el-table-column prop="createdAt" label="创建时间" width="200" align="center" sortable>
        <template slot-scope="scope">
          {{ scope.row.createdAt | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template slot-scope="scope" v-if="scope.row.id !== 1">
          <el-switch
              v-model="scope.row.status"
              :active-value="0"
              :inactive-value="1"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="updateRolesStatus(scope.row.id)"
          ></el-switch>
          <span>{{ scope.row.status === 0 ? '开启' : '禁用' }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="updatedAt" label="修改时间" width="200" align="center" sortable>
        <template slot-scope="scope">
          {{ scope.row.updatedAt | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="assignMenu(scope.row)">分配菜单</el-button>
          <template v-if="scope.row.id !== 1">
            <el-button type="success" size="mini" @click="editRole(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="deleteRole(scope.row.id)">删除</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!--  3.模态框-->
    <!-- 1.新增角色-->
    <!-- 新增角色模态框 -->
    <el-dialog :visible.sync="showAddModal" title="新增" width="30%" custom-class="my-dialog">
      <!--  label-width="100px"添加宽间距-->
      <el-form :model="newRoleForm" ref="newRoleForm" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="newRoleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="newRoleForm.description"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="showAddModal = false">取消</el-button>
        <el-button type="primary" @click="saveNewRole">保存</el-button>
      </div>
    </el-dialog>

    <!-- 2.编辑-->
    <el-dialog :visible.sync="showEditModal" title="编辑" width="30%" custom-class="my-dialog">
      <div class="dialog-content">
        <el-form :model="editRoleForm" ref="editRoleForm" label-width="80px">
          <el-form-item label="角色id" prop="id">
            <el-input v-model="editRoleForm.id" readonly></el-input>
          </el-form-item>
          <el-form-item label="角色名称">
            <el-input v-model="editRoleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="editRoleForm.description"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-footer">
        <el-button @click="showEditModal = false">取消</el-button>
        <el-button type="primary" @click="saveEditedRole">保存</el-button>
      </div>
    </el-dialog>

    <!-- 3.分配菜单-->
    <el-dialog
        title="分配菜单"
        :visible.sync="dialogVisible"
        width="30%"
    >
      <div max-height="250">
        <el-tree
            ref="treeRef"
            :data="menus"
            :show-checkbox="true"
            default-expand-all
            :expand-on-click-node="true"
            :default-checked-keys="selectedMenuIds"
            node-key="id"
            highlight-current
            :props="defaultProps"
            @check="handleMenuCheck"
        ></el-tree>
      </div>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveMenuAssignment">保存菜单分配</el-button>
      </div>
    </el-dialog>


    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[3, 5, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>
</template>


<script>
import {MessageBox} from "element-ui";

export default {
  data() {
    return {
      selectedMenuIds: [],  // 拥有的菜单
      roleId: null,
      checkedMenuIds: [], // 已选中的菜单项ID
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      menus: [], // 存储从后端获取的菜单数据
      selectedMenus: [], // 存储用户选择的菜单
      dialogVisible: false, // 分配菜单模态框
      editRoleForm: {
        id: null,
        name: null,
        description: null,
      }, // 用于编辑的角色表单数据
      showEditModal: false, // 编辑角色模态框的显示状态
      showAddModal: false,
      newRoleForm: {// 新增角色表单数据
        name: null,
        description: null,
      },
      form: {searchText: ''}, // 搜索表单数据
      roleData: [], // 角色数据
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页记录数
      total: 0, // 总条数
    };
  },
  created() {
    this.getRoles();
    this.fetchMenus();
  },
  methods: {
    open4() {
      this.$notify({
        title: '',
        message: '操作成功',
        position: 'top-left',
        type: 'success'
      });
    },
    // 获取所有的菜单
    async fetchMenus() {
      const response = await this.$http.get('/community/menu/getMenus');
      this.menus = response.data; // 将获取到的菜单数据存储在 Vue 实例的数据中
    },

    // 修改状态
    async updateRolesStatus(status) {
      // 发送请求到后端，修改角色的状态
      const url = `/community/role/updateRolesStatus/${status}`;
      await this.$http.post(url);
    },

    // 分配菜单按钮
    assignMenu(row) {
      this.dialogVisible = true;
      // 检查是否存在 this.$refs.treeRef，如果不存在则等待一段时间后再次尝试调用
      if (this.$refs.treeRef) {
        // 清空上一次选中的数据
        this.$refs.treeRef.setCheckedKeys([])

        this.roleId = row.id

        const selectedMenuIds = []; // 创建一个数组来存储选中的菜单ID

        // 如果 row.menus 的父级 ID 为 null，则不将其放入集合中
        row.menus.forEach(menu => {
          if (!menu.parentId) {
            return; // 退出当前循环，不执行后续操作
          } else {
            // 获取到 menu 的 id，放在集合中
            selectedMenuIds.push(menu.id + '');
          }
        });
        // 最后将获取到的集合放在 :default-checked-keys="[2]"  将【2】替换成selectedMenuIds
        this.selectedMenuIds = selectedMenuIds;
      } else {
        setTimeout(() => {
          // 清空上一次选中的数据
          this.$refs.treeRef.setCheckedKeys([])

          this.roleId = row.id

          const selectedMenuIds = []; // 创建一个数组来存储选中的菜单ID

          // 如果 row.menus 的父级 ID 为 null，则不将其放入集合中
          row.menus.forEach(menu => {
            if (!menu.parentId) {
              return; // 退出当前循环，不执行后续操作
            } else {
              // 获取到 menu 的 id，放在集合中
              selectedMenuIds.push(menu.id + '');
            }
          });
          // 最后将获取到的集合放在 :default-checked-keys="[2]"  将【2】替换成selectedMenuIds
          this.selectedMenuIds = selectedMenuIds;
        }, 10); // 等待500毫秒后再次尝试调用
      }
    },

    async saveMenuAssignment() {
      // 保存菜单分配的逻辑
      const checkedMenus = this.$refs.treeRef.getCheckedNodes(); // 获取用户选择的菜单项 整行数据

      this.selectedMenuIds = []; // 初始化为一个空数组

      checkedMenus.forEach(e => {
        this.selectedMenuIds.push(e.id); // 将每个菜单项的ID添加到数组中
      });

      // 如果parentId 不等于对象的Id，那么就在后端插入这条父级，即可解决
      await this.$http.post(`/community/role/saveMenuAssignment/${this.roleId}`, checkedMenus)

      this.open4()


      // 查询新的数据
      await this.fetchMenus();
      await this.getRoles();
      // 在这里处理保存逻辑，可以将选中的菜单项发送给后端进行保存
      this.dialogVisible = false; // 关闭模态框


    },
    handleMenuCheck(checkedKeys) {
      // 用户勾选/取消勾选菜单项时触发
      this.checkedMenuIds = checkedKeys;
    },

    // 编辑后保存
    async saveEditedRole() {
      await this.$http.post('/community/role/editRole', this.editRoleForm)
      this.$message.success("成功修改成：  " + this.editRoleForm.name)

      // 刷新同时关闭模态框
      await this.getRoles();
      this.showEditModal = false;
    },

    // 编辑角色
    editRole(role) {
      this.editRoleForm = role;
      this.showEditModal = true;
    },

    // 删除角色方法
    async deleteRole(id) {
      MessageBox.confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await this.$http.post(`/community/role/deleteRole/` + id);
        this.$message.success('员工删除成功');
        await this.getRoles();
      }).catch(() => {
        // 取消删除操作 or 错误处理
        this.$message.error('已取消操作');
      });
    },
    // 新增角色
    async saveNewRole() {
      const response = await this.$http.post(`/community/role/addRole`, this.newRoleForm);
      this.$message.success("添加" + this.newRoleForm.name + "角色成功")
      this.showAddModal = false; // 关闭模态框
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.getRoles();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.getRoles();
    },
    // 查询角色方法
    async getRoles() {
      const params = {
        name: this.form.searchText,
      };
      const response = await this.$http.post(`/community/role/getRoles/${this.currentPage}/${this.pageSize}`, params);

      this.roleData = response.data.list; // 角色数据列表
      this.total = response.data.total; // 总条数
    },
  }
}
</script>

<style>
.dialogMaxHeight {
  max-height: 400px; /* 限制最大高度为400px，根据需要调整 */
  overflow-y: auto; /* 启用垂直滚动条 */
}
</style>